package yxt.net.websocket.example.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import yxt.net.websocket.example.message.RequestMessage;
import yxt.net.websocket.example.message.ResponseMessage;

import java.nio.charset.StandardCharsets;

/**
 * <p>
 * 文本处理器
 * </p>
 *
 * @author zhangxiaolin
 * @since 2022/1/24$ 15:14$
 */
@Component
public class TextWebSocketAction extends TextWebSocketHandler {
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("<---------------afterConnectionEstablished------------->" + session.getId());
    }

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> webSocketMessage) throws Exception {
        System.out.println("<-----------handleMessage----------------->" + webSocketMessage.isLast());
        //  String name = (String) session.getAttributes().get("name");
        String data = webSocketMessage.getPayload().toString();
        RequestMessage chatText = objectMapper.readValue(data, RequestMessage.class);
        ResponseMessage resMessage = new ResponseMessage("回应消息", chatText.getText());
        String res = objectMapper.writeValueAsString(resMessage);
        TextMessage textMessage = new TextMessage(res.getBytes(StandardCharsets.UTF_8));
        session.sendMessage(textMessage);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("<--------------handleTransportError-------------->");
        exception.printStackTrace();
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        System.out.println("<---------------------------->" + session.getId());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
